// src/hooks/useNodeIndex.js
import { ref, computed } from 'vue'

/**
 * 节点索引管理 Hook
 * @param {Array} initialFields - 初始字段数据
 * @returns {Object} 索引管理相关方法和状态
 */
export function useNodeIndex(initialFields = []) {
  // 响应式状态
  const fields = ref([...initialFields])
  const nodeIndexById = ref(new Map())
  const nodeIndexByName = ref(new Map())
  const indexStats = ref({ byId: 0, byName: 0, total: 0 })

  /**
   * 构建索引缓存 - 递归遍历一次，后续查找O(1)
   */
  const buildNodeIndex = (fieldsData = fields.value) => {
    // 清空现有索引
    nodeIndexById.value.clear()
    nodeIndexByName.value.clear()
    
    let totalNodes = 0
    
    const traverse = (nodes, parentPath = '', parentNode = null) => {
      nodes.forEach((node, index) => {
        totalNodes++
        const currentPath = parentPath ? `${parentPath}.children.${index}` : `${index}`
        
        // 节点信息对象
        const nodeInfo = {
          node,
          path: currentPath,
          parent: parentNode,
          index,
          level: parentPath.split('.children.').length - 1
        }
        
        // 建立索引映射
        if (node.id) {
          nodeIndexById.value.set(node.id, nodeInfo)
        }
        
        if (node.name) {
          nodeIndexByName.value.set(node.name, nodeInfo)
        }
        
        // 递归处理子节点
        if (node.children && Array.isArray(node.children)) {
          traverse(node.children, currentPath, node)
        }
      })
    }
    
    traverse(fieldsData)
    
    // 更新统计信息
    indexStats.value = {
      byId: nodeIndexById.value.size,
      byName: nodeIndexByName.value.size,
      total: totalNodes
    }
    
    console.log('索引构建完成', indexStats.value)
  }

  /**
   * 根据路径获取节点
   */
  const getNodeByPath = (path) => {
    if (!path) return null
    
    const pathArray = path.split('.')
    let current = fields.value
    
    try {
      for (let i = 0; i < pathArray.length; i += 2) {
        const index = parseInt(pathArray[i])
        current = current[index]
        
        if (i + 2 < pathArray.length && pathArray[i + 1] === 'children') {
          current = current.children
        }
      }
      return current
    } catch (error) {
      console.warn('路径无效:', path, error)
      return null
    }
  }

  /**
   * 高效查找节点数据 - O(1) 时间复杂度
   */
  const getNodeData = (fieldNameOrId) => {
    if (!fieldNameOrId) return null
    
    // 先按ID查找
    const nodeInfoById = nodeIndexById.value.get(fieldNameOrId)
    if (nodeInfoById) {
      return nodeInfoById.node
    }
    
    // 再按Name查找
    const nodeInfoByName = nodeIndexByName.value.get(fieldNameOrId)
    if (nodeInfoByName) {
      return nodeInfoByName.node
    }
    
    return null
  }

  /**
   * 获取节点详细信息（包含路径、父节点等）
   */
  const getNodeInfo = (fieldNameOrId) => {
    if (!fieldNameOrId) return null
    
    return nodeIndexById.value.get(fieldNameOrId) || 
           nodeIndexByName.value.get(fieldNameOrId) || 
           null
  }

  /**
   * 获取节点的父节点
   */
  const getParentNode = (fieldNameOrId) => {
    const nodeInfo = getNodeInfo(fieldNameOrId)
    return nodeInfo?.parent || null
  }

  /**
   * 获取节点的所有子节点
   */
  const getChildNodes = (fieldNameOrId) => {
    const node = getNodeData(fieldNameOrId)
    return node?.children || []
  }

  /**
   * 获取节点的兄弟节点
   */
  const getSiblingNodes = (fieldNameOrId) => {
    const nodeInfo = getNodeInfo(fieldNameOrId)
    if (!nodeInfo) return []
    
    const parent = nodeInfo.parent
    if (parent && parent.children) {
      return parent.children.filter(sibling => sibling.id !== nodeInfo.node.id)
    }
    
    // 如果是根节点，返回其他根节点
    return fields.value.filter(sibling => sibling.id !== nodeInfo.node.id)
  }

  /**
   * 批量查找节点
   * @param {Array} ids - 节点ID数组
   * @returns {Array} 节点数组
   */
  const getNodesByIds = (ids) => {
    return ids.map(id => getNodeData(id)).filter(Boolean)
  }

  /**
   * 根据条件查找节点
   * @param {Function} predicate - 条件函数
   * @returns {Array} 节点数组
   */
  const findNodes = (predicate) => {
    const results = []
    
    // 遍历所有索引的节点
    for (const nodeInfo of nodeIndexById.value.values()) {
      if (predicate(nodeInfo.node, nodeInfo)) {
        results.push(nodeInfo.node)
      }
    }
    
    return results
  }

  /**
   * 根据类型查找节点
   * @param {String} type - 节点类型
   * @returns {Array} 节点数组
   */
  const getNodesByType = (type) => {
    return findNodes(node => node.type === type)
  }

  /**
   * 获取指定层级的所有节点
   * @param {Number} level - 节点层级
   * @returns {Array} 节点数组
   */
  const getNodesByLevel = (level) => {
    return findNodes((node, nodeInfo) => nodeInfo.level === level)
  }

  /**
   * 添加新节点并更新索引
   * @param {Object} node - 新节点
   * @param {String} parentId - 父节点ID
   * @param {Number} index - 插入位置索引
   */
  const addNode = (node, parentId = null, index = -1) => {
    if (parentId) {
      const parentNode = getNodeData(parentId)
      if (parentNode) {
        if (!parentNode.children) {
          parentNode.children = []
        }
        
        if (index === -1) {
          parentNode.children.push(node)
        } else {
          parentNode.children.splice(index, 0, node)
        }
      }
    } else {
      if (index === -1) {
        fields.value.push(node)
      } else {
        fields.value.splice(index, 0, node)
      }
    }
    
    // 重建索引
    buildNodeIndex()
  }

  /**
   * 删除节点并更新索引
   * @param {String} fieldNameOrId - 节点ID或名称
   * @returns {Boolean} 是否删除成功
   */
  const removeNode = (fieldNameOrId) => {
    const nodeInfo = getNodeInfo(fieldNameOrId)
    if (!nodeInfo) return false
    
    const parent = nodeInfo.parent
    if (parent && parent.children) {
      const index = parent.children.findIndex(child => 
        child.id === nodeInfo.node.id || child.name === nodeInfo.node.name
      )
      if (index > -1) {
        parent.children.splice(index, 1)
      }
    } else {
      // 删除根节点
      const index = fields.value.findIndex(node => 
        node.id === nodeInfo.node.id || node.name === nodeInfo.node.name
      )
      if (index > -1) {
        fields.value.splice(index, 1)
      }
    }
    
    // 重建索引
    buildNodeIndex()
    return true
  }

  /**
   * 更新节点数据
   * @param {String} fieldNameOrId - 节点ID或名称
   * @param {Object} updates - 更新数据
   * @returns {Boolean} 是否更新成功
   */
  const updateNode = (fieldNameOrId, updates) => {
    const node = getNodeData(fieldNameOrId)
    if (node) {
      Object.assign(node, updates)
      // 如果更新了id或name，需要重建索引
      if (updates.id || updates.name) {
        buildNodeIndex()
      }
      return true
    }
    return false
  }

  /**
   * 更新整个字段数据并重建索引
   * @param {Array} newFields - 新的字段数据
   */
  const updateFields = (newFields) => {
    fields.value = [...newFields]
    buildNodeIndex()
  }

  /**
   * 清空所有数据
   */
  const clear = () => {
    fields.value = []
    nodeIndexById.value.clear()
    nodeIndexByName.value.clear()
    indexStats.value = { byId: 0, byName: 0, total: 0 }
  }

  /**
   * 获取索引统计信息
   */
  const getIndexStats = () => indexStats.value

  /**
   * 检查节点是否存在
   * @param {String} fieldNameOrId - 节点ID或名称
   * @returns {Boolean} 是否存在
   */
  const hasNode = (fieldNameOrId) => {
    return nodeIndexById.value.has(fieldNameOrId) || 
           nodeIndexByName.value.has(fieldNameOrId)
  }

  // 计算属性：所有节点的扁平化列表
  const allNodes = computed(() => {
    return Array.from(nodeIndexById.value.values()).map(info => info.node)
  })

  // 计算属性：根节点列表
  const rootNodes = computed(() => {
    return fields.value
  })

  // 计算属性：叶子节点列表
  const leafNodes = computed(() => {
    return findNodes(node => !node.children || node.children.length === 0)
  })

  return {
    // 状态
    fields,
    indexStats,
    
    // 计算属性
    allNodes,
    rootNodes,
    leafNodes,
    
    // 索引管理
    buildNodeIndex,
    clear,
    getIndexStats,
    
    // 查找方法
    getNodeData,
    getNodeInfo,
    getNodeByPath,
    getParentNode,
    getChildNodes,
    getSiblingNodes,
    getNodesByIds,
    getNodesByType,
    getNodesByLevel,
    findNodes,
    hasNode,
    
    // 数据操作
    addNode,
    removeNode,
    updateNode,
    updateFields
  }
}
